package com.chunlei.complete.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/12/8 0:15
 */
@Service
public class JoinService
{
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    public void testFuture()
    {
//        for (int i = 0; i < 100000; i++)
//        {
//            System.out.println(i);
//        }
//        System.out.println("第二件事！");
        CompletableFuture<Void> v1 = CompletableFuture.runAsync(() -> {
            for (int i = 0; i < 10000; i++)
            {
                //System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }, threadPoolExecutor);
        CompletableFuture<Void> v2 = CompletableFuture.runAsync(() -> {
            //System.out.println(a);
            System.out.println("第二件事！");
        });

        //等待所有的异步任务全部完成
        try
        {
            CompletableFuture.allOf(v1, v2).get();
            System.out.println("来了！");
        } catch (InterruptedException | ExecutionException e)
        {
            e.printStackTrace();
        }
    }
}
